package jjn.round1;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Jjn
 * @since 2022-10-05 10:18
 */
public class LeetCode811_SubDomainVisitCount {
    public List<String> subdomainVisits(String[] cpdomains) {
        Map<String, Integer> visitCountMap = new HashMap<>();
        for (String domain : cpdomains) {
            analyseDomain(domain, visitCountMap);
        }
        return getResult(visitCountMap);
    }
    
    private List<String> getResult(Map<String, Integer> visitCountMap) {
        if (visitCountMap == null || visitCountMap.isEmpty()) {
            return List.of();
        }
        List<String> domainCounts = new ArrayList<>();
        visitCountMap.forEach((domain, count) -> {
            domainCounts.add(count + " " + domain);
        });
        return domainCounts;
    }
    
    private void analyseDomain(String domain, Map<String, Integer> visitCountMap) {
        if (domain == null || domain.length() == 0) {
            return;
        }
        String[] parts = domain.split(" ");
        int count = Integer.parseInt(parts[0]);
        String domainInfo = parts[1];
        String[] domainParts = domainInfo.split("\\.");
        int length = domainParts.length;
        StringBuilder base = new StringBuilder();
        for (int i = length - 1; i >= 0; i--) {
            base.insert(0, domainParts[i]);
            Integer current = visitCountMap.getOrDefault(base.toString(), 0);
            visitCountMap.put(base.toString(), current + count);
            base.insert(0, ".");
        }
    }
}
